<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>万字长文详解Java泛型 | 风祈的时光录</title><meta name="keywords" content="Java基础，泛型"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="万字长文详解Java泛型。">
<meta property="og:type" content="article">
<meta property="og:title" content="万字长文详解Java泛型">
<meta property="og:url" content="https://imlql.cn/post/adb2faf0.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="万字长文详解Java泛型。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://upyunimg.imlql.cn/lql_static@latest/logo/java.png">
<meta property="article:published_time" content="2020-10-19T14:21:58.000Z">
<meta property="article:modified_time" content="2022-07-24T11:02:09.866Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="基础">
<meta property="article:tag" content="泛型">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://upyunimg.imlql.cn/lql_static@latest/logo/java.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/adb2faf0"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '万字长文详解Java泛型',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:02:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://upyunimg.imlql.cn/lql_static@latest/logo/java.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">万字长文详解Java泛型</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-10-19T14:21:58.000Z" title="发表于 2020-10-19 22:21:58">2020-10-19</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:02:09.866Z" title="更新于 2022-07-24 19:02:09">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java%E5%9F%BA%E7%A1%80/">Java基础</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java%E5%9F%BA%E7%A1%80/%E9%87%8D%E9%9A%BE%E7%82%B9/">重难点</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">11.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>48分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h1><h2 id="泛型的优点"><a href="#泛型的优点" class="headerlink" title="泛型的优点"></a>泛型的优点</h2><p>1、泛型的本质是为了参数化类型，也就是在在不创建新的类型的情况下，通过泛型指定的不同类型来控制形参具体限制的类型，很明显这种方法提高了代码的复用性。</p>
<p>2、泛型的引入提高了安全性，泛型提供了编译时类型安全检测机制，该机制允许开发者在编译时检测到非法的类型。。</p>
<p>3、在没有泛型的情况的下，通过对类型 Object 的引用来实现参数的“任意化”，“任意化”带来的缺点是要做显式的强制类型转换，而这种转换是要求开发者对实际参数类型可以预知的情况下进行的。对于强制类型转换错误的情况，编译器可能不提示错误，在运行的时候才出现异常，这是本身就是一个安全隐患。</p>
<p>那么泛型的好处就是在编译的时候能够检查类型安全，并且所有的强制转换都是自动和隐式的。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GlmapperGeneric</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">		<span class="keyword">private</span> T t;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">set</span><span class="params">(T t)</span> </span>&#123; <span class="keyword">this</span>.t = t; &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">get</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> t; &#125;</span><br><span class="line">  </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// do nothing</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 不指定类型</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">noSpecifyType</span><span class="params">()</span></span>&#123;</span><br><span class="line">    GlmapperGeneric glmapperGeneric = <span class="keyword">new</span> GlmapperGeneric();</span><br><span class="line">    glmapperGeneric.set(<span class="string">&quot;test&quot;</span>);</span><br><span class="line">    <span class="comment">// 需要强制类型转换</span></span><br><span class="line">    String test = (String) glmapperGeneric.get();</span><br><span class="line">    System.out.println(test);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 指定类型</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">specifyType</span><span class="params">()</span></span>&#123;</span><br><span class="line">    GlmapperGeneric&lt;String&gt; glmapperGeneric = <span class="keyword">new</span> GlmapperGeneric();</span><br><span class="line">    glmapperGeneric.set(<span class="string">&quot;test&quot;</span>);</span><br><span class="line">    <span class="comment">// 不需要强制类型转换</span></span><br><span class="line">    String test = glmapperGeneric.get();</span><br><span class="line">    System.out.println(test);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="为什么提高了安全性？"><a href="#为什么提高了安全性？" class="headerlink" title="为什么提高了安全性？"></a>为什么提高了安全性？</h2><p>再举例子说明一下</p>
<p><strong>不安全举例</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.Generic;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/15 16:09</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述:</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_Safe</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        test();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List arrayList = <span class="keyword">new</span> ArrayList();</span><br><span class="line">        arrayList.add(<span class="string">&quot;aaaa&quot;</span>);</span><br><span class="line">        arrayList.add(<span class="number">100</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; arrayList.size(); i++) &#123;</span><br><span class="line">            String s = (String) arrayList.get(i);</span><br><span class="line">            System.out.println(s);</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;    </span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">aaaa</span><br><span class="line">Exception in thread &quot;main&quot; java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String</span><br><span class="line">	at keyAndDifficultPoints.Generic.Test_Safe.test(Test_Safe.java:25)</span><br><span class="line">	at keyAndDifficultPoints.Generic.Test_Safe.main(Test_Safe.java:16)</span><br></pre></td></tr></table></figure>

<p>很明显的一个类型转换错误。ArrayList可以存放任意类型，例子中添加了一个String类型，添加了一个Integer类型，再使用时都以String的方式使用，因此程序崩溃了。为了解决类似这样的问题（在编译阶段就可以解决），泛型应运而生。</p>
<p><strong>泛型提高安全性</strong></p>
<p>将上面的代码稍微改一下</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test01</span><span class="params">()</span></span>&#123;</span><br><span class="line">       List&lt;String&gt; arrayList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">       arrayList.add(<span class="string">&quot;aaaa&quot;</span>);</span><br><span class="line">       <span class="comment">//下面代码编译时就直接报错了</span></span><br><span class="line">       arrayList.add(<span class="number">100</span>);</span><br><span class="line"></span><br><span class="line">       <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; arrayList.size(); i++) &#123;</span><br><span class="line">           String s = (String) arrayList.get(i);</span><br><span class="line">           System.out.println(s);</span><br><span class="line"></span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>通过泛型来提前检测类型，编译时就通不过。</p>
<h2 id="泛型为什么很重要"><a href="#泛型为什么很重要" class="headerlink" title="泛型为什么很重要"></a>泛型为什么很重要</h2><p>我们看一下比较常用的JUC包</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;U&gt; <span class="function">CompletableFuture&lt;U&gt; <span class="title">thenComposeAsync</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Function&lt;? <span class="keyword">super</span> T, ? extends CompletionStage&lt;U&gt;&gt; fn)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> uniComposeStage(asyncPool, fn);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> &lt;U&gt; <span class="function">CompletableFuture&lt;U&gt; <span class="title">thenComposeAsync</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        Function&lt;? <span class="keyword">super</span> T, ? extends CompletionStage&lt;U&gt;&gt; fn,</span></span></span><br><span class="line"><span class="function"><span class="params">        Executor executor)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> uniComposeStage(screenExecutor(executor), fn);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> CompletableFuture&lt;T&gt; <span class="title">whenComplete</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        BiConsumer&lt;? <span class="keyword">super</span> T, ? <span class="keyword">super</span> Throwable&gt; action)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> uniWhenCompleteStage(<span class="keyword">null</span>, action);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> CompletableFuture&lt;T&gt; <span class="title">whenCompleteAsync</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        BiConsumer&lt;? <span class="keyword">super</span> T, ? <span class="keyword">super</span> Throwable&gt; action)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> uniWhenCompleteStage(asyncPool, action);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>这些都大量的用到了泛型，如果不把泛型学好，想真正深入源码了解一些东西，可能就完全看不懂了。</p>
<h1 id="泛型类"><a href="#泛型类" class="headerlink" title="泛型类"></a>泛型类</h1><p>泛型类型用于类的定义中，被称为泛型类。通过泛型可以完成对一组类的操作对外开放相同的接口。最典型的就是各种容器类，如：List、Set、Map。</p>
<p><strong>最普通的泛型类：</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.Generic;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/15 16:38</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述:</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_GenericClass</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        test();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 1、泛型的类型参数只能是类类型（包括自定义类），不能是简单数据类型（比如int,long这些）</span></span><br><span class="line"><span class="comment">         * 2、传入的实参类型需与泛型的类型参数类型相同，即为这里的Integer。</span></span><br><span class="line"><span class="comment">         * 3、new 后面的泛型参数可以省略</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        Generic&lt;Integer&gt; genericInteger1 = <span class="keyword">new</span> Generic&lt;Integer&gt;(<span class="number">123</span>);</span><br><span class="line">        Generic&lt;Integer&gt; genericInteger = <span class="keyword">new</span> Generic&lt;&gt;(<span class="number">123</span>);</span><br><span class="line"></span><br><span class="line">        Generic&lt;String&gt; genericString = <span class="keyword">new</span> Generic&lt;String&gt;(<span class="string">&quot;my&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(genericInteger.getVar());</span><br><span class="line">        System.out.println(genericString.getVar());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 1、此处T虽然可以随便写为任意标识，常见的如T、E、K、V等形式的参数常用于表示泛型。</span></span><br><span class="line"><span class="comment"> * 但是为了代码的可读性一般来说：</span></span><br><span class="line"><span class="comment"> * K,V用来表示键值对</span></span><br><span class="line"><span class="comment"> * E是Element的缩写，常用来遍历时表示</span></span><br><span class="line"><span class="comment"> * T就是Type的缩写，常用在普通泛型类上</span></span><br><span class="line"><span class="comment"> * 2、还有一些不常见的U,R啥的</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Generic</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">//key这个成员变量的类型为T,T的类型由外部指定</span></span><br><span class="line">    <span class="keyword">private</span> T <span class="keyword">var</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Generic</span><span class="params">(T <span class="keyword">var</span>)</span> </span>&#123; <span class="comment">//泛型构造方法形参key的类型也为T，T的类型由外部指定</span></span><br><span class="line">        <span class="keyword">this</span>.<span class="keyword">var</span> = <span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getVar</span><span class="params">()</span> </span>&#123; <span class="comment">//泛型方法getKey的返回值类型为T，T的类型由外部指定</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyMap</span>&lt;<span class="title">K</span>, <span class="title">V</span>&gt; </span>&#123;       <span class="comment">// 此处指定了两个泛型类型</span></span><br><span class="line">    <span class="keyword">private</span> K key;     <span class="comment">// 此变量的类型由外部决定</span></span><br><span class="line">    <span class="keyword">private</span> V value;   <span class="comment">// 此变量的类型由外部决定</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> K <span class="title">getKey</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.key;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> V <span class="title">getValue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setKey</span><span class="params">(K key)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.key = key;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setValue</span><span class="params">(V value)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.value = value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p><strong>结果：</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">123</span><br><span class="line">my</span><br><span class="line"></span><br><span class="line">Process finished with exit code 0</span><br></pre></td></tr></table></figure>



<ul>
<li>定义的泛型类，就一定要传入泛型类型实参么？并不是这样，在使用泛型的时候如果传入泛型实参，则会根据传入的泛型实参做相应的限制，此时泛型才会起到本应起到的限制作用。如果不传入泛型类型实参的话，在泛型类中使用泛型的方法或成员变量定义的类型可以为任何的类型。</li>
</ul>
<p>还是以上面的泛型类为例进行测试</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test01</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       Generic generic = <span class="keyword">new</span> Generic(<span class="string">&quot;我是字符串&quot;</span>);</span><br><span class="line">       Generic generic1 = <span class="keyword">new</span> Generic(<span class="number">123</span>);</span><br><span class="line">       Generic generic2 = <span class="keyword">new</span> Generic(<span class="number">123.123</span>);</span><br><span class="line">       Generic generic3 = <span class="keyword">new</span> Generic(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">       System.out.println(generic.getVar());</span><br><span class="line">       System.out.println(generic1.getVar());</span><br><span class="line">       System.out.println(generic2.getVar());</span><br><span class="line">       System.out.println(generic3.getVar());</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p><strong>结果：</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">我是字符串</span><br><span class="line">123</span><br><span class="line">123.123</span><br><span class="line">false</span><br><span class="line"></span><br><span class="line">Process finished with exit code 0</span><br></pre></td></tr></table></figure>

<p>没有报错，正确输出了。</p>
<h1 id="泛型接口"><a href="#泛型接口" class="headerlink" title="泛型接口"></a>泛型接口</h1><p>泛型接口与泛型类的定义及使用基本相同。泛型接口常被用在各种类的生产器中，可以看一个例子：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">interface</span> <span class="title">Info</span>&lt;<span class="title">T</span>&gt;</span>&#123;        <span class="comment">// 在接口上定义泛型  </span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getVar</span><span class="params">()</span> </span>; <span class="comment">// 定义方法，方法的返回值就是泛型类型  </span></span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>

<p><strong>当实现泛型接口的类，未传入泛型实参时：</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 未传入泛型实参时，与泛型类的定义相同，在声明类的时候，需将泛型的声明也一起加到类中</span></span><br><span class="line"><span class="comment"> * 即：class InfoImpl&lt;T&gt; implements Info&lt;T&gt;</span></span><br><span class="line"><span class="comment"> * 如果不声明泛型，如：class InfoImpl implements Info&lt;T&gt;，编译器会报错：&quot;Unknown class&quot;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">InfoImpl</span>&lt;<span class="title">T</span>&gt; <span class="keyword">implements</span> <span class="title">Info</span>&lt;<span class="title">T</span>&gt; </span>&#123;   <span class="comment">// 定义泛型接口的子类</span></span><br><span class="line">    <span class="keyword">private</span> T <span class="keyword">var</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">InfoImpl</span><span class="params">(T <span class="keyword">var</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.setVar(<span class="keyword">var</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setVar</span><span class="params">(T <span class="keyword">var</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.<span class="keyword">var</span> = <span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getVar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.<span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当实现泛型接口的类，传入泛型实参时：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 传入泛型实参时：</span></span><br><span class="line"><span class="comment"> * 定义一个是先烈实现这个接口,虽然我们只创建了一个泛型接口Info&lt;T&gt;</span></span><br><span class="line"><span class="comment"> * 在实现类实现泛型接口时，如已将泛型类型传入实参类型，则所有使用泛型的地方都要替换成传入的实参类型</span></span><br><span class="line"><span class="comment"> * 即：InfoImpl01&lt;T&gt;，public String getVar();中的的T都要替换成传入的String类型。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">InfoImpl01</span> <span class="keyword">implements</span> <span class="title">Info</span>&lt;<span class="title">String</span>&gt; </span>&#123;   <span class="comment">// 定义泛型接口的子类</span></span><br><span class="line">    <span class="keyword">private</span> String <span class="keyword">var</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">InfoImpl01</span><span class="params">(String <span class="keyword">var</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.setVar(<span class="keyword">var</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setVar</span><span class="params">(String <span class="keyword">var</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.<span class="keyword">var</span> = <span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getVar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.<span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="泛型方法"><a href="#泛型方法" class="headerlink" title="泛型方法"></a>泛型方法</h1><p>在java中，泛型类和接口的定义非常简单，但是泛型方法就比较复杂了。</p>
<p>泛型类，是在实例化类的时候指明泛型的具体类型；泛型方法，是在调用方法的时候指明泛型的具体类型。</p>
<p><strong>最简单的一个泛型方法</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_GenericMethod</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Test_GenericMethod test_genericMethod = <span class="keyword">new</span> Test_GenericMethod();</span><br><span class="line">        Integer integer = test_genericMethod.genericMethod(<span class="number">12</span>);</span><br><span class="line">        System.out.println(integer);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 说明：</span></span><br><span class="line"><span class="comment">     * 1、public 与 返回值中间&lt;T&gt;非常重要，可以理解为声明此方法为泛型方法。</span></span><br><span class="line"><span class="comment">     * 2、只有声明了&lt;T&gt;的方法才是泛型方法，泛型类中的使用了泛型的成员方法并不是泛型方法。</span></span><br><span class="line"><span class="comment">     * 3、&lt;T&gt;表明该方法将使用泛型类型T，此时才可以在方法中使用泛型类型T。</span></span><br><span class="line"><span class="comment">     * 4、&lt;T&gt; 后面的这个T，代表这个方法的返回值类型</span></span><br><span class="line"><span class="comment">     * 4、与泛型类的定义一样，此处T可以随便写为任意标识，常见的如T、E、K、V等形式的参数常用于表示泛型。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> &lt;T&gt; <span class="function">T <span class="title">genericMethod</span><span class="params">(T a)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> a;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h2 id="基本用法（非泛型类中的泛型方法）"><a href="#基本用法（非泛型类中的泛型方法）" class="headerlink" title="基本用法（非泛型类中的泛型方法）"></a>基本用法（非泛型类中的泛型方法）</h2><p>下面来细说一下泛型方法</p>
<p>首先说一个误区</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Generic01</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T key;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Generic01</span><span class="params">(T key)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.key = key;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1、这个虽然在方法中使用了泛型，但这并不是一个泛型方法。这只是类中一个普通的</span></span><br><span class="line"><span class="comment">     * 成员方法，只不过他的返回值是在声明泛型类已经声明过的泛型。所以在这个方法中才</span></span><br><span class="line"><span class="comment">     * 可以继续使用 T 这个泛型。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getKey</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> key;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1、这个方法显然是有问题的，在编译器会给我们提示这样的错误信息&quot;cannot reslove symbol E&quot;</span></span><br><span class="line"><span class="comment">     * 因为在类的声明中并未声明泛型E，所以在使用E做形参和返回值类型时，编译器会无法识别。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="comment">//    public E setKey(E key) &#123;</span></span><br><span class="line"><span class="comment">//        this.key = key;</span></span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>基本用法</strong>（非）</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.Generic;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/15 17:46</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述:</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_GenericMethod</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Test_GenericMethod test_genericMethod = <span class="keyword">new</span> Test_GenericMethod();</span><br><span class="line">        Generic01&lt;Integer&gt; generic01 = <span class="keyword">new</span> Generic01&lt;&gt;(<span class="number">123</span>);</span><br><span class="line"></span><br><span class="line">        Generic01&lt;String&gt; generic02 = <span class="keyword">new</span> Generic01&lt;&gt;(<span class="string">&quot;AAAAA&quot;</span>);</span><br><span class="line"></span><br><span class="line">        test_genericMethod.genericMethod_test01(generic01);</span><br><span class="line">        test_genericMethod.genericMethod_test02(generic02, <span class="string">&quot;我是T&quot;</span>);</span><br><span class="line"></span><br><span class="line">        test_genericMethod.Method01(generic01);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 说明：</span></span><br><span class="line"><span class="comment">     * 1、public 与 返回值中间&lt;T&gt;非常重要，可以理解为声明此方法为泛型方法。</span></span><br><span class="line"><span class="comment">     * 2、只有声明了&lt;T&gt;的方法才是泛型方法，泛型类中的使用了泛型的成员方法并不是泛型方法。</span></span><br><span class="line"><span class="comment">     * 3、&lt;T&gt;表明该方法将使用泛型类型T，此时才可以在方法中使用泛型类型T。</span></span><br><span class="line"><span class="comment">     * 4、&lt;T&gt; 后面的这个T，代表这个方法的返回值类型</span></span><br><span class="line"><span class="comment">     * 4、与泛型类的定义一样，此处T可以随便写为任意标识，常见的如T、E、K、V等形式的参数常用于表示泛型。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> &lt;T&gt; <span class="function">T <span class="title">genericMethod</span><span class="params">(T a)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> a;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1、这才是一个真正的泛型方法。</span></span><br><span class="line"><span class="comment">     * 2、首先在public与返回值之间的&lt;T&gt;必不可少，这表明这是一个泛型方法，并且声明了一个泛型T。</span></span><br><span class="line"><span class="comment">     * 3、这个T可以出现在这个泛型方法的任意位置.泛型的数量也可以为任意多个</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> &lt;T&gt; <span class="function">T <span class="title">genericMethod_test01</span><span class="params">(Generic01&lt;T&gt; generic01)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;我是genericMethod_test01：&quot;</span> + generic01.getKey());</span><br><span class="line">        T test = generic01.getKey();</span><br><span class="line">        <span class="keyword">return</span> test;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> &lt;T, V&gt; <span class="function">T <span class="title">genericMethod_test02</span><span class="params">(Generic01&lt;T&gt; generic01, V value)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;我是genericMethod_test02：&quot;</span> + generic01.getKey() + <span class="string">&quot;==&gt; value：&quot;</span> + value);</span><br><span class="line"></span><br><span class="line">        T test = generic01.getKey();</span><br><span class="line">        <span class="keyword">return</span> test;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//这也不是一个泛型方法，这就是一个普通的方法，只是使用了Generic&lt;Number&gt;这个泛型类做形参而已。</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Method01</span><span class="params">(Generic01&lt;? extends Number&gt; generic01)</span> </span>&#123;</span><br><span class="line">        System.out.println(generic01.getKey());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//这也不是一个泛型方法，这也是一个普通的方法，只不过使用了泛型通配符?</span></span><br><span class="line">    <span class="comment">//同时这也印证了泛型通配符章节所描述的，?是一种类型实参，可以看做为Number等所有类的父类</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Method02</span><span class="params">(Generic01&lt;?&gt; generic01)</span> </span>&#123;</span><br><span class="line">        System.out.println(generic01.getKey());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 这个方法是有问题的，编译器会为我们提示错误信息：&quot;UnKnown class &#x27;E&#x27; &quot;</span></span><br><span class="line"><span class="comment">     * 虽然我们声明了&lt;T&gt;,也表明了这是一个可以处理泛型的类型的泛型方法。</span></span><br><span class="line"><span class="comment">     * 但是只声明了泛型类型T，并未声明泛型类型E，因此编译器并不知道该如何处理E这个类型。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="comment">//    public &lt;T&gt; T showKeyName(Generic01&lt;E&gt; generic01, T t) &#123;</span></span><br><span class="line"><span class="comment">//        return t;</span></span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>结果：</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">我是genericMethod_test01：123</span><br><span class="line">我是genericMethod_test02：AAAAA&#x3D;&#x3D;&gt; value：我是T</span><br><span class="line">123</span><br><span class="line"></span><br><span class="line">Process finished with exit code 0</span><br></pre></td></tr></table></figure>

<h2 id="泛型类中的泛型方法"><a href="#泛型类中的泛型方法" class="headerlink" title="泛型类中的泛型方法"></a>泛型类中的泛型方法</h2><p>当然这并不是泛型方法的全部，泛型方法可以出现杂任何地方和任何场景中使用。但是有一种情况是非常特殊的，当泛型方法出现在泛型类中时，我们再通过一个例子看一下。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.Generic;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/15 20:14</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述:</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_GenericMethod01</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Apple apple = <span class="keyword">new</span> Apple();</span><br><span class="line">        Person person = <span class="keyword">new</span> Person();</span><br><span class="line"></span><br><span class="line">        GenerateTest&lt;Fruit&gt; generateTest = <span class="keyword">new</span> GenerateTest&lt;Fruit&gt;();</span><br><span class="line">        <span class="comment">//apple是Fruit的子类，所以这里可以</span></span><br><span class="line">        generateTest.show_1(apple);</span><br><span class="line">        <span class="comment">//编译器会报错，因为泛型类型实参指定的是Fruit，而传入的实参类是Person</span></span><br><span class="line">        <span class="comment">//generateTest.show_1(person);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//使用这两个方法都可以成功</span></span><br><span class="line">        generateTest.show_2(apple);</span><br><span class="line">        generateTest.show_2(person);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//使用这两个方法也都可以成功</span></span><br><span class="line">        generateTest.show_3(apple);</span><br><span class="line">        generateTest.show_3(person);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">GenericFruit</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Fruit</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;fruit&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Apple</span> <span class="keyword">extends</span> <span class="title">Fruit</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;apple&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Person&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GenerateTest</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">show_1</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">        System.out.println(t.toString());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1、在泛型类中声明了一个泛型方法，使用泛型E，这种泛型E可以为任意类型。可以类型与T相同，也可以不同。</span></span><br><span class="line"><span class="comment">     * 2、由于泛型方法在声明的时候会声明泛型&lt;E&gt;，因此即使在泛型类中并未声明泛型，编译器也能够正确识别</span></span><br><span class="line"><span class="comment">     泛型方法中识别的泛型。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> &lt;E&gt; <span class="function"><span class="keyword">void</span> <span class="title">show_3</span><span class="params">(E t)</span> </span>&#123;</span><br><span class="line">        System.out.println(t.toString());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1、在泛型类中声明了一个泛型方法，使用泛型T，注意这个T是一种全新的类型，可以与泛型类中声明的T</span></span><br><span class="line"><span class="comment">     * 不是同一种类型。也就是说main函数中使用的时候也可以是不一样的泛型类型</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">show_2</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">        System.out.println(t.toString());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>结果：</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">apple</span><br><span class="line">apple</span><br><span class="line">Person</span><br><span class="line">apple</span><br><span class="line">Person</span><br><span class="line"></span><br><span class="line">Process finished with exit code 0</span><br></pre></td></tr></table></figure>



<h2 id="泛型方法与可变参数"><a href="#泛型方法与可变参数" class="headerlink" title="泛型方法与可变参数"></a>泛型方法与可变参数</h2><p>再看一个泛型方法和可变参数的例子：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_GenericMethod02</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        print(<span class="string">&quot;123&quot;</span>,<span class="number">753</span>,<span class="number">123.12</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//必须是三个点</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">print</span><span class="params">(T... args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (T t : args) &#123;</span><br><span class="line">            System.out.println(t);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>结果：</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">123</span><br><span class="line">753</span><br><span class="line">123.12</span><br><span class="line"></span><br><span class="line">Process finished with exit code 0</span><br></pre></td></tr></table></figure>

<h2 id="静态方法与泛型"><a href="#静态方法与泛型" class="headerlink" title="静态方法与泛型"></a>静态方法与泛型</h2><p>静态方法有一种情况需要注意一下，那就是在类中的静态方法使用泛型：<strong>静态方法无法访问类上定义的泛型；如果静态方法操作的引用数据类型不确定的时候，必须要将泛型定义在方法上。</strong></p>
<p>即：<strong>如果静态方法要使用泛型的话，必须将静态方法也定义成泛型方法</strong> 。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StaticGenerator</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1、如果在类中定义使用泛型的静态方法，需要添加额外的泛型声明（将这个方法定义成泛型方法）</span></span><br><span class="line"><span class="comment">     * 即使静态方法要使用泛型类中已经声明过的泛型也不可以。</span></span><br><span class="line"><span class="comment">     * 如：public static void show(T t)&#123;..&#125;,此时编译器会提示错误信息：</span></span><br><span class="line"><span class="comment">          &quot;StaticGenerator cannot be refrenced from static context&quot;</span></span><br><span class="line"><span class="comment">     * 2、泛型方法：在方法中出现了泛型的结构，泛型参数与类的泛型参数没有任何关系。换句话说，</span></span><br><span class="line"><span class="comment">     * 泛型方法所属的类是不是泛型类都没有关系。</span></span><br><span class="line"><span class="comment">     * 3、泛型方法，可以声明为静态的。原因：泛型参数是在调用方法时确定的。并非在初始化类时确定,所以无所谓</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;E&gt;  <span class="function">List&lt;E&gt; <span class="title">copyFromArrayToList</span><span class="params">(E[] arr)</span></span>&#123;</span><br><span class="line"></span><br><span class="line">        ArrayList&lt;E&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span>(E e : arr)&#123;</span><br><span class="line">            list.add(e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> list;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="细枝末节"><a href="#细枝末节" class="headerlink" title="细枝末节"></a>细枝末节</h2><blockquote>
<p>可能合上面的有一些重复</p>
</blockquote>
<p>1、泛型异常类</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&#x2F;&#x2F;异常类不能声明为泛型类，编译报错</span><br><span class="line">class MyException&lt;T&gt; extends Exception&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>2、</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.Generic.Minutiae;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/15 22:28</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述:</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_Minutiae1</span> </span>&#123;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Order</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    String orderName;</span><br><span class="line">    <span class="keyword">int</span> orderId;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//类的内部结构就可以使用类的泛型</span></span><br><span class="line"></span><br><span class="line">    T orderT;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Order</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">//编译不通过</span></span><br><span class="line"><span class="comment">//        T[] arr = new T[10];</span></span><br><span class="line">        <span class="comment">//编译通过</span></span><br><span class="line">        T[] arr = (T[]) <span class="keyword">new</span> Object[<span class="number">10</span>];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Order</span><span class="params">(String orderName,<span class="keyword">int</span> orderId,T orderT)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.orderName = orderName;</span><br><span class="line">        <span class="keyword">this</span>.orderId = orderId;</span><br><span class="line">        <span class="keyword">this</span>.orderT = orderT;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//如下的三个方法都不是泛型方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getOrderT</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> orderT;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setOrderT</span><span class="params">(T orderT)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.orderT = orderT;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Order&#123;&quot;</span> +</span><br><span class="line">                <span class="string">&quot;orderName=&#x27;&quot;</span> + orderName + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, orderId=&quot;</span> + orderId +</span><br><span class="line">                <span class="string">&quot;, orderT=&quot;</span> + orderT +</span><br><span class="line">                <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//静态方法中不能使用类的泛型。</span></span><br><span class="line"><span class="comment">//    public static void show(T orderT)&#123;</span></span><br><span class="line"><span class="comment">//        System.out.println(orderT);</span></span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">show</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">//编译不通过</span></span><br><span class="line"><span class="comment">//        try&#123;</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//        &#125;catch(T t)&#123;</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//        &#125;</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 2、泛型方法：在方法中出现了泛型的结构，泛型参数与类的泛型参数没有任何关系。换句话说，</span></span><br><span class="line"><span class="comment">     * 泛型方法所属的类是不是泛型类都没有关系。</span></span><br><span class="line"><span class="comment">     * 3、泛型方法，可以声明为静态的。原因：泛型参数是在调用方法时确定的。并非在初始化类时确定,</span></span><br><span class="line"><span class="comment">     * 所以无所谓</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;E&gt; <span class="function">List&lt;E&gt; <span class="title">copyFromArrayToList</span><span class="params">(E[] arr)</span></span>&#123;</span><br><span class="line"></span><br><span class="line">        ArrayList&lt;E&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span>(E e : arr)&#123;</span><br><span class="line">            list.add(e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> list;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SubOrder</span> <span class="keyword">extends</span> <span class="title">Order</span>&lt;<span class="title">Integer</span>&gt; </span>&#123;<span class="comment">//SubOrder:不是泛型类</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;E&gt; <span class="function">List&lt;E&gt; <span class="title">copyFromArrayToList</span><span class="params">(E[] arr)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        ArrayList&lt;E&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (E e : arr) &#123;</span><br><span class="line">            list.add(e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> list;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SubOrder1</span>&lt;<span class="title">T</span>&gt; <span class="keyword">extends</span> <span class="title">Order</span>&lt;<span class="title">T</span>&gt; </span>&#123;<span class="comment">//SubOrder1&lt;T&gt;:仍然是泛型类</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>







<h1 id="泛型数组"><a href="#泛型数组" class="headerlink" title="泛型数组"></a>泛型数组</h1><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.Generic;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/15 12:10</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述: 测试泛型数组</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_GenericArray</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        test02();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//编译错误</span></span><br><span class="line"><span class="comment">//        List&lt;String&gt;[] ls = new ArrayList&lt;String&gt;[10];</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test01</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//这样声明是正确的</span></span><br><span class="line">        List&lt;?&gt;[] ls = <span class="keyword">new</span> ArrayList&lt;?&gt;[<span class="number">10</span>];</span><br><span class="line">        ls[<span class="number">1</span>] = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//这样写编译就报错了</span></span><br><span class="line"><span class="comment">//        ls[1].add(1);</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 下面是sun官方文档里写的。其实不用太纠结，平时泛型虽然用的多，但也不会用的这么奇葩。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test02</span><span class="params">()</span></span>&#123;</span><br><span class="line">        List&lt;?&gt;[] lsa = <span class="keyword">new</span> List&lt;?&gt;[<span class="number">10</span>]; <span class="comment">// OK, array of unbounded wildcard type.</span></span><br><span class="line">        Object o = lsa;</span><br><span class="line">        Object[] oa = (Object[]) o;</span><br><span class="line">        List&lt;Integer&gt; li = <span class="keyword">new</span> ArrayList&lt;Integer&gt;();</span><br><span class="line">        li.add(<span class="keyword">new</span> Integer(<span class="number">3</span>));</span><br><span class="line">        oa[<span class="number">1</span>] = li; <span class="comment">// Correct.</span></span><br><span class="line">        Integer i = (Integer) lsa[<span class="number">1</span>].get(<span class="number">0</span>); <span class="comment">// OK</span></span><br><span class="line">        System.out.println(i);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//正确</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test03</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;String&gt;[] ls = <span class="keyword">new</span> ArrayList[<span class="number">10</span>];</span><br><span class="line">        ls[<span class="number">0</span>] = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">        ls[<span class="number">1</span>] = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line"></span><br><span class="line">        ls[<span class="number">0</span>].add(<span class="string">&quot;x&quot;</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><a target="_blank" rel="noopener" href="http://docs.oracle.com/javase/tutorial/extra/generics/fineprint.html">sun文档</a></p>
<h1 id="泛型在继承方面的细节"><a href="#泛型在继承方面的细节" class="headerlink" title="泛型在继承方面的细节"></a>泛型在继承方面的细节</h1><p>直接看代码注释</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"> <span class="comment">/*</span></span><br><span class="line"><span class="comment">    1. 泛型在继承方面的体现</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">      虽然类A是类B的父类，但是G&lt;A&gt; 和G&lt;B&gt;二者不具备子父类关系，二者是并列关系。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">       补充：类A是类B的父类，A&lt;G&gt; 是 B&lt;G&gt; 的父类</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 下面是有继承关系，所以可以赋值</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        Object obj = <span class="keyword">null</span>;</span><br><span class="line">        String str = <span class="keyword">null</span>;</span><br><span class="line">        obj = str;</span><br><span class="line"></span><br><span class="line">        Object[] arr1 = <span class="keyword">null</span>;</span><br><span class="line">        String[] arr2 = <span class="keyword">null</span>;</span><br><span class="line">        arr1 = arr2;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 下面属于并列关系，无继承关系。无法赋值</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//编译不通过</span></span><br><span class="line"><span class="comment">//        Date date = new Date();</span></span><br><span class="line"><span class="comment">//        str = date;</span></span><br><span class="line">        List&lt;Object&gt; list1 = <span class="keyword">null</span>;</span><br><span class="line">        List&lt;String&gt; list2 = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">        <span class="comment">//此时的list1和list2的类型不具有子父类关系</span></span><br><span class="line">        <span class="comment">//编译不通过</span></span><br><span class="line"><span class="comment">//        list1 = list2;</span></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        反证法：</span></span><br><span class="line"><span class="comment">        假设list1 = list2;</span></span><br><span class="line"><span class="comment">           list1.add(123);导致混入非String的数据。出错。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test2</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        AbstractList&lt;String&gt; list1 = <span class="keyword">null</span>;</span><br><span class="line">        List&lt;String&gt; list2 = <span class="keyword">null</span>;</span><br><span class="line">        ArrayList&lt;String&gt; list3 = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">        list1 = list3;</span><br><span class="line">        list2 = list3;</span><br><span class="line"></span><br><span class="line">        List&lt;String&gt; list4 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>



<h1 id="泛型通配符"><a href="#泛型通配符" class="headerlink" title="泛型通配符"></a>泛型通配符</h1><p>我们在定义泛型类，泛型方法，泛型接口的时候经常会碰见很多不同的通配符，比如 T，E，K，V，？ 等等，下面来详细讲一下这些通配符。</p>
<h2 id="常用的通配符"><a href="#常用的通配符" class="headerlink" title="常用的通配符"></a>常用的通配符</h2><p>本质上都是通配符没啥区别，只不过是编码时的一种约定俗成的东西（可以说提高了代码可读性）。比如上述代码中的 T ，我们可以换成 A-Z 之间的任何一个大小写字母都可以，并不会影响程序的正常运行，但是如果换成其他的字母代替 T ，在可读性上可能会弱一些。通常情况下，T，E，K，V，？ 是这样约定的：</p>
<ul>
<li>  ？ 表示不确定的 java 类型</li>
<li>  T (Type) 表示具体的一个java类型</li>
<li>  K V (Key Value) 分别代表java键值中的Key Value</li>
<li>  E (element) 代表Element</li>
</ul>
<p>比较难的就是<code>？</code>通配符，下面就着重讲一下</p>
<h2 id="‘-‘无界通配符"><a href="#‘-‘无界通配符" class="headerlink" title="‘ ? ‘无界通配符"></a>‘ ? ‘无界通配符</h2><h3 id="基本用法"><a href="#基本用法" class="headerlink" title="基本用法"></a>基本用法</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;Animal&gt; listAnimals</span><br></pre></td></tr></table></figure>

<p>但是如果用通配符的话：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">List&lt;? extends Animal&gt; listAnimals</span><br></pre></td></tr></table></figure>

<p>为什么要使用通配符而不是简单的泛型呢？通配符其实在声明局部变量时是没有什么意义的，但是当你为一个方法声明一个参数时，它是非常重要的。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.Generic;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/15 21:25</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述: 泛型通配符测试</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_Wildcard_Character</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;Dog&gt; dogList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        test(dogList);</span><br><span class="line">        test1(dogList);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">(List&lt;? extends Animal&gt; animals)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;test输出:&quot;</span>);</span><br><span class="line">        <span class="keyword">for</span> (Animal animal : animals) &#123;</span><br><span class="line">            System.out.print(animal.toString() + <span class="string">&quot;-&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test1</span><span class="params">(List&lt;Animal&gt; animals)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;test1输出:&quot;</span>);</span><br><span class="line">        <span class="keyword">for</span> (Animal animal : animals) &#123;</span><br><span class="line">            System.out.print(animal.toString() + <span class="string">&quot;-&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Animal&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dog</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Dog&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>test1()</code>在编译时就会飘红</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/Java_Basis/Generic/0001.png">



<p>所以，对于不确定或者不关心实际要操作的类型，可以使用无限制通配符（尖括号里一个问号，即 &lt;?&gt; ），表示可以持有任何类型。像 <code>test()</code>方法中，限定了上界，但是不关心具体类型是什么，所以对于传入的 Animal 的所有子类都可以支持，并且不会报错，而<code>test1()</code>就不行。</p>
<h3 id="‘-‘通配符的继承"><a href="#‘-‘通配符的继承" class="headerlink" title="‘ ? ‘通配符的继承"></a>‘ ? ‘通配符的继承</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    2. 通配符的使用</span></span><br><span class="line"><span class="comment">       通配符：?</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">       类A是类B的父类，G&lt;A&gt;和G&lt;B&gt;是没有关系的，二者共同的父类是：G&lt;?&gt;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test3</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;Object&gt; list1 = <span class="keyword">null</span>;</span><br><span class="line">        List&lt;String&gt; list2 = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">        List&lt;?&gt; list = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">        list = list1;</span><br><span class="line">        list = list2;</span><br><span class="line">        <span class="comment">//编译通过</span></span><br><span class="line"><span class="comment">//        print(list1);</span></span><br><span class="line"><span class="comment">//        print(list2);</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//</span></span><br><span class="line">        List&lt;String&gt; list3 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        list3.add(<span class="string">&quot;AA&quot;</span>);</span><br><span class="line">        list3.add(<span class="string">&quot;BB&quot;</span>);</span><br><span class="line">        list3.add(<span class="string">&quot;CC&quot;</span>);</span><br><span class="line">        list = list3;</span><br><span class="line">        <span class="comment">//添加(写入)：对于List&lt;?&gt;就不能向其内部添加数据。</span></span><br><span class="line">        <span class="comment">//除了添加null之外。</span></span><br><span class="line"><span class="comment">//        list.add(&quot;DD&quot;);</span></span><br><span class="line"><span class="comment">//        list.add(&#x27;?&#x27;);</span></span><br><span class="line"></span><br><span class="line">        list.add(<span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取(读取)：允许读取数据，读取的数据类型为Object。</span></span><br><span class="line">        Object o = list.get(<span class="number">0</span>);</span><br><span class="line">        System.out.println(o);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>



<h2 id="extends和super上下界"><a href="#extends和super上下界" class="headerlink" title="extends和super上下界"></a>extends和super上下界</h2><h3 id="上界通配符-lt-extends-E-gt"><a href="#上界通配符-lt-extends-E-gt" class="headerlink" title="上界通配符 &lt; ? extends E&gt;"></a>上界通配符 &lt; ? extends E&gt;</h3><blockquote>
<p>上结：用 extends 关键字声明，表示参数化的类型可能是所指定的类型，或者是此类型的子类。</p>
</blockquote>
<p>在类型参数中使用 extends 表示这个泛型中的参数必须是 E 或者 E 的子类，这样有两个好处：</p>
<ul>
<li>如果传入的类型不是 E 或者 E 的子类，编译不成功</li>
<li>泛型中可以使用 E 的方法，要不然还得强转成 E 才能使用</li>
</ul>
<h3 id="下界通配符-lt-super-E-gt"><a href="#下界通配符-lt-super-E-gt" class="headerlink" title="下界通配符 &lt; ? super E&gt;"></a>下界通配符 &lt; ? super E&gt;</h3><blockquote>
<p>下界: 用 super 进行声明，表示参数化的类型可能是所指定的类型，或者是此类型的父类型，直至 Object</p>
</blockquote>
<p>在类型参数中使用 super 表示这个泛型中的参数必须是 E 或者 E 的父类。</p>
<h3 id="举例"><a href="#举例" class="headerlink" title="举例"></a>举例</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"> <span class="comment">/*</span></span><br><span class="line"><span class="comment">    3.有限制条件的通配符的使用。</span></span><br><span class="line"><span class="comment">        ? extends A:</span></span><br><span class="line"><span class="comment">                G&lt;? extends A&gt; 可以作为G&lt;A&gt;和G&lt;B&gt;的父类，其中B是A的子类</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">        ? super A:</span></span><br><span class="line"><span class="comment">                G&lt;? super A&gt; 可以作为G&lt;A&gt;和G&lt;B&gt;的父类，其中B是A的父类</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test4</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        List&lt;? extends Person&gt; list1 = <span class="keyword">null</span>; <span class="comment">//[-无穷,Person]</span></span><br><span class="line">        List&lt;? <span class="keyword">super</span> Person&gt; list2 = <span class="keyword">null</span>;  <span class="comment">//[Person,+无穷]</span></span><br><span class="line"></span><br><span class="line">        List&lt;Student&gt; list3 = <span class="keyword">new</span> ArrayList&lt;Student&gt;();</span><br><span class="line">        List&lt;Person&gt; list4 = <span class="keyword">new</span> ArrayList&lt;Person&gt;();</span><br><span class="line">        List&lt;Object&gt; list5 = <span class="keyword">new</span> ArrayList&lt;Object&gt;();</span><br><span class="line"></span><br><span class="line">        list1 = list3;</span><br><span class="line">        list1 = list4;</span><br><span class="line"><span class="comment">//        list1 = list5;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        list2 = list3;</span></span><br><span class="line">        list2 = list4;</span><br><span class="line">        list2 = list5;</span><br><span class="line"></span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line">        <span class="comment">//下面的东西很奇怪</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//读取数据：</span></span><br><span class="line">        list1 = list3;</span><br><span class="line">        Person p = list1.get(<span class="number">0</span>);</span><br><span class="line">        <span class="comment">//编译不通过</span></span><br><span class="line">        <span class="comment">//Student s = list1.get(0);</span></span><br><span class="line"></span><br><span class="line">        list2 = list4;</span><br><span class="line">        Object obj = list2.get(<span class="number">0</span>);</span><br><span class="line">        <span class="comment">////编译不通过</span></span><br><span class="line"><span class="comment">//        Person obj = list2.get(0);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//写入数据：</span></span><br><span class="line">        <span class="comment">//编译不通过</span></span><br><span class="line"><span class="comment">//        list1.add(new Student());</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//编译通过</span></span><br><span class="line">        list2.add(<span class="keyword">new</span> Person());</span><br><span class="line">        list2.add(<span class="keyword">new</span> Student());</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span> <span class="keyword">extends</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>##？ 和 T 的区别</p>
<p>？和 T 都表示不确定的类型，区别在于我们可以对 T 进行操作，但是对 ？ 不行，比如如下这种 ：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 可以</span></span><br><span class="line">T t = operate();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 不可以</span></span><br><span class="line">？ car = operate();</span><br></pre></td></tr></table></figure>

<p>简单总结下：</p>
<p>T 是一个 确定的 类型，通常用于泛型类和泛型方法的定义，？是一个 不确定 的类型，通常用于泛型方法的调用代码和形参，不能用于定义类和泛型方法。</p>
<h3 id="区别1：通过T来确保泛型参数的一致性"><a href="#区别1：通过T来确保泛型参数的一致性" class="headerlink" title="区别1：通过T来确保泛型参数的一致性"></a>区别1：通过T来确保泛型参数的一致性</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.Wildcard_Character;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/16 11:28</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述:</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_difference</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; integerList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        List&lt;Float&gt; floatList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//编译报错</span></span><br><span class="line"><span class="comment">//        test(integerList, floatList);</span></span><br><span class="line">        <span class="comment">//编译通过</span></span><br><span class="line">        test1(integerList, floatList);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//编译通过</span></span><br><span class="line">        test(integerList, integerList);</span><br><span class="line">        test1(integerList, integerList);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 通过 T 来 确保 泛型参数的一致性</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T extends Number&gt; <span class="function"><span class="keyword">void</span> <span class="title">test</span><span class="params">(List&lt;T&gt; dest, List&lt;T&gt; src)</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通配符是 不确定的，所以这个方法不能保证两个 List 具有相同的元素类型</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test1</span><span class="params">(List&lt;? extends Number&gt; dest, List&lt;? extends Number&gt; src)</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="区别2：T可以通过-amp-进行多重限定"><a href="#区别2：T可以通过-amp-进行多重限定" class="headerlink" title="区别2：T可以通过&amp;进行多重限定"></a>区别2：T可以通过&amp;进行多重限定</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_difference</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">/*---------------------测试多重限定符---------------------*/</span></span><br><span class="line">        ArrayList list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        ArrayDeque deque = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        LinkedList&lt;Object&gt; linkedList = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//多重限定时，在编译的时候取最小范围或共同子类</span></span><br><span class="line"></span><br><span class="line">        test2(list);</span><br><span class="line"><span class="comment">//        test3(list); 编译报错</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//编译报错</span></span><br><span class="line"><span class="comment">//        test2(deque);</span></span><br><span class="line"><span class="comment">//        test3(deque);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//编译通过</span></span><br><span class="line">        test2(linkedList);</span><br><span class="line">        test3(linkedList);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//可以进行多重限定</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T extends List &amp; Collection&gt; <span class="function"><span class="keyword">void</span> <span class="title">test2</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//可以进行多重限定</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T extends Queue &amp; List&gt; <span class="function"><span class="keyword">void</span> <span class="title">test3</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//编译报错，无法进行多重限定</span></span><br><span class="line"><span class="comment">//    public static &lt;? extends List &amp; Collection&gt; void test4(List&lt;T&gt; dest, List&lt;T&gt; src)&#123;</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/Java_Basis/Generic/0002.png">

<h3 id="区别3：？通配符可以使用超类限定而T不行"><a href="#区别3：？通配符可以使用超类限定而T不行" class="headerlink" title="区别3：？通配符可以使用超类限定而T不行"></a>区别3：？通配符可以使用超类限定而T不行</h3><p>类型参数 T 只具有 一种 类型限定方式：</p>
<pre><code>T extends A
</code></pre>
<p>但是通配符 ? 可以进行 两种限定：</p>
<pre><code>? extends A
? super A
</code></pre>
<hr>
<h1 id="关于反射和泛型的一点东西"><a href="#关于反射和泛型的一点东西" class="headerlink" title="关于反射和泛型的一点东西"></a>关于反射和泛型的一点东西</h1><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.Wildcard_Character;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/16 12:09</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述: 泛型反射</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_Reflect</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> ClassNotFoundException, IllegalAccessException, InstantiationException </span>&#123;</span><br><span class="line">        A a = createInstance(A.class);</span><br><span class="line">        B b = createInstance(B.class);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 这样写明显是要安全很多的</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">createInstance</span><span class="params">(Class&lt;T&gt; clazz)</span> <span class="keyword">throws</span> IllegalAccessException, InstantiationException </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> clazz.newInstance();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">getA</span><span class="params">(String path)</span> <span class="keyword">throws</span> ClassNotFoundException, IllegalAccessException, InstantiationException </span>&#123;</span><br><span class="line">        A a = (A) Class.forName(<span class="string">&quot;keyAndDifficultPoints.Wildcard_Character.A&quot;</span>).newInstance();</span><br><span class="line">        <span class="comment">//很明显下面的这行代码是错的，但是写代码的时候你不知道path是哪个</span></span><br><span class="line"><span class="comment">//        B b = (B)Class.forName(&quot;keyAndDifficultPoints.Wildcard_Character.A&quot;).newInstance();</span></span><br><span class="line">        System.out.println(a.toString());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">    String name;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;我是对象A&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> </span>&#123;</span><br><span class="line">    String name;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;我是对象B&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span> </span>&#123;</span><br><span class="line">    <span class="comment">//所以当不知道声明什么类型的 Class 的时候可以定义一 个Class&lt;?&gt;。</span></span><br><span class="line">    <span class="keyword">public</span> Class&lt;?&gt; clazz1;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//因为T没有声明，所以编译报错</span></span><br><span class="line"><span class="comment">//    public Class&lt;T&gt; clazz2;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">D</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> Class&lt;?&gt; clazz;</span><br><span class="line">    <span class="comment">// 不会报错</span></span><br><span class="line">    <span class="keyword">public</span> Class&lt;T&gt; clazzT;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h1 id="泛型原理（泛型擦除）"><a href="#泛型原理（泛型擦除）" class="headerlink" title="泛型原理（泛型擦除）"></a>泛型原理（泛型擦除）</h1><h2 id="类型擦除简介"><a href="#类型擦除简介" class="headerlink" title="类型擦除简介"></a>类型擦除简介</h2><p>​    Java的泛型是伪泛型，为什么说Java的泛型是伪泛型呢？因为在编译期间，所有的泛型信息都会被擦除掉，我们常称为<strong>泛型擦除</strong>。</p>
<p>​    Java中的泛型基本上都是在编译器这个层次来实现的，在生成的Java字节码中是不包含泛型中的类型信息的。使用泛型的时候加上的类型参数，编译器在编译的时候去掉，这个过程就称为类型擦除。</p>
<p>​    如在代码中定义的<code>List&lt;object&gt;</code>和<code>List&lt;String&gt;</code>等类型，在编译后都会编程List，JVM看到的只是List。而由泛型附加的类型信息对JVM来说是不可见的。Java编译器会在编译时尽可能的发现可能出错的地方，但是仍然无法避免在运行时刻出现类型转换异常的情况。类型擦除也是Java的泛型实现方法与C++模版机制实现方式之间的重要区别。</p>
<p>可以通过两个例子，来证明java泛型的类型擦除。</p>
<p><strong>例1：</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">     List&lt;String&gt; stringList = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">     stringList.add(<span class="string">&quot;my&quot;</span>);</span><br><span class="line">     List&lt;Integer&gt; integerList = <span class="keyword">new</span> ArrayList&lt;Integer&gt;();</span><br><span class="line">     integerList.add(<span class="number">123</span>);</span><br><span class="line">     System.out.println(stringList.getClass() == integerList.getClass());</span><br><span class="line"></span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<p><strong>结果：</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">true</span><br><span class="line"></span><br><span class="line">Process finished with exit code 0</span><br></pre></td></tr></table></figure>

<p>在这个例子中，我们定义了两个List，不过一个是List<String>泛型类型，只能存储字符串。一个是List<Integer>泛型类型，只能存储整形。最后，我们通过stringList对象和integerList对象的getClass方法获取它们的类的信息，最后发现结果为true。说明泛型类型String和Integer都被擦除掉了，只剩下了原始类型。</p>
<p><strong>例2：</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"> <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test01</span><span class="params">()</span> <span class="keyword">throws</span> NoSuchMethodException, InvocationTargetException, IllegalAccessException </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; list = <span class="keyword">new</span> ArrayList&lt;Integer&gt;();</span><br><span class="line">        <span class="comment">//这样调用add方法只能存储整形，因为泛型类型的实例为Integer</span></span><br><span class="line">        list.add(<span class="number">1</span>);</span><br><span class="line">        <span class="comment">//这样写编译就会报错</span></span><br><span class="line"><span class="comment">//        list.add(&quot;my&quot;);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//通过反射的方式则可以存储String</span></span><br><span class="line">        list.getClass().getMethod(<span class="string">&quot;add&quot;</span>, Object.class).invoke(list, <span class="string">&quot;my&quot;</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; list.size(); i++) &#123;</span><br><span class="line">            System.out.println(list.get(i));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">1</span><br><span class="line">my</span><br><span class="line"></span><br><span class="line">Process finished with exit code 0</span><br></pre></td></tr></table></figure>

<p>在程序中定义了一个List<Integer>泛型类型，如果直接调用add方法，那么只能存储整形的数据。不过当我们利用反射调用add方法的时候，却可以存储字符串。这说明了Integer泛型实例在编译之后被擦除了，只保留了 原始类型。</p>
<h2 id="类型擦除后保留的原始类型"><a href="#类型擦除后保留的原始类型" class="headerlink" title="类型擦除后保留的原始类型"></a>类型擦除后保留的原始类型</h2><p>1、在上面，几次提到了<strong>原始类型</strong>。什么是原始类型？原始类型就是擦除去了泛型信息，最后在字节码中的类型变量的真正类型。无论何时定义一个泛型类型，相应的原始类型都会被自动地提供。类型变量被擦除，并使用其限定类型（无限定的变量用Object替换）。</p>
<p>例3：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.principle;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/16 23:01</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述:</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_principle02</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test_Generic</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T value;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getValue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setValue</span><span class="params">(T value)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.value = value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>下面我们用IDEA的工具，查看这个类的字节码信息。我把完整的字节码复制在下方：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// class version 52.0 (52)</span></span><br><span class="line"><span class="comment">// access flags 0x20</span></span><br><span class="line"><span class="comment">// signature &lt;T:Ljava/lang/Object;&gt;Ljava/lang/Object;</span></span><br><span class="line"><span class="comment">// declaration: keyAndDifficultPoints/principle/Test_Generic&lt;T&gt;</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">keyAndDifficultPoints</span>/<span class="title">principle</span>/<span class="title">Test_Generic</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// compiled from: Test_principle02.java</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x2</span></span><br><span class="line">  <span class="comment">// signature TT;</span></span><br><span class="line">  <span class="comment">// declaration: T</span></span><br><span class="line">  <span class="keyword">private</span> Ljava/lang/Object; value</span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x0</span></span><br><span class="line">  &lt;init&gt;()V</span><br><span class="line">   L0</span><br><span class="line">    LINENUMBER <span class="number">13</span> L0</span><br><span class="line">    ALOAD <span class="number">0</span></span><br><span class="line">    INVOKESPECIAL java/lang/Object.&lt;init&gt; ()V</span><br><span class="line">    RETURN</span><br><span class="line">   L1</span><br><span class="line">    LOCALVARIABLE <span class="keyword">this</span> LkeyAndDifficultPoints/principle/Test_Generic; L0 L1 <span class="number">0</span></span><br><span class="line">    <span class="comment">// signature LkeyAndDifficultPoints/principle/Test_Generic&lt;TT;&gt;;</span></span><br><span class="line">    <span class="comment">// declaration: keyAndDifficultPoints.principle.Test_Generic&lt;T&gt;</span></span><br><span class="line">    MAXSTACK = <span class="number">1</span></span><br><span class="line">    MAXLOCALS = <span class="number">1</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x1</span></span><br><span class="line">  <span class="comment">// signature ()TT;</span></span><br><span class="line">  <span class="comment">// declaration: T getValue()</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">getValue</span><span class="params">()</span>Ljava/lang/Object</span>;</span><br><span class="line">   L0</span><br><span class="line">    LINENUMBER <span class="number">17</span> L0</span><br><span class="line">    ALOAD <span class="number">0</span></span><br><span class="line">    GETFIELD keyAndDifficultPoints/principle/Test_Generic.value : Ljava/lang/Object;</span><br><span class="line">    ARETURN</span><br><span class="line">   L1</span><br><span class="line">    LOCALVARIABLE <span class="keyword">this</span> LkeyAndDifficultPoints/principle/Test_Generic; L0 L1 <span class="number">0</span></span><br><span class="line">    <span class="comment">// signature LkeyAndDifficultPoints/principle/Test_Generic&lt;TT;&gt;;</span></span><br><span class="line">    <span class="comment">// declaration: keyAndDifficultPoints.principle.Test_Generic&lt;T&gt;</span></span><br><span class="line">    MAXSTACK = <span class="number">1</span></span><br><span class="line">    MAXLOCALS = <span class="number">1</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x1</span></span><br><span class="line">  <span class="comment">// signature (TT;)V</span></span><br><span class="line">  <span class="comment">// declaration: void setValue(T)</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">setValue</span><span class="params">(Ljava/lang/Object;)</span>V</span></span><br><span class="line"><span class="function">   L0</span></span><br><span class="line"><span class="function">    LINENUMBER 21 L0</span></span><br><span class="line"><span class="function">    ALOAD 0</span></span><br><span class="line"><span class="function">    ALOAD 1</span></span><br><span class="line"><span class="function">    PUTFIELD keyAndDifficultPoints/principle/Test_Generic.value : Ljava/lang/Object</span>;</span><br><span class="line">   L1</span><br><span class="line">    LINENUMBER <span class="number">22</span> L1</span><br><span class="line">    RETURN</span><br><span class="line">   L2</span><br><span class="line">    LOCALVARIABLE <span class="keyword">this</span> LkeyAndDifficultPoints/principle/Test_Generic; L0 L2 <span class="number">0</span></span><br><span class="line">    <span class="comment">// signature LkeyAndDifficultPoints/principle/Test_Generic&lt;TT;&gt;;</span></span><br><span class="line">    <span class="comment">// declaration: keyAndDifficultPoints.principle.Test_Generic&lt;T&gt;</span></span><br><span class="line">    LOCALVARIABLE value Ljava/lang/Object; L0 L2 <span class="number">1</span></span><br><span class="line">    <span class="comment">// signature TT;</span></span><br><span class="line">    <span class="comment">// declaration: T</span></span><br><span class="line">    MAXSTACK = <span class="number">2</span></span><br><span class="line">    MAXLOCALS = <span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>可以明显的看到<strong>泛型T</strong>被替换成了<strong>Object</strong>。</p>
<p>​    因为在Test_Generic<T>中，T是一个无限定的类型变量，所以用Object替换。其结果就是一个普通的类，如同泛型加入java变成语言之前已经实现的那样。在程序中可以包含不同类型的Test_Generic，如Test_Generic<String>或Test_Generic<Integer>，但是，擦除类型后它们就成为原始的Test_Generic类型了，原始类型都是Object。</p>
<p>​    从上面的那个例2中，我们也可以明白List<Integer>被擦除类型后，原始类型也变成了Object，所以通过反射我们就可以存储字符串了。</p>
<p>2、如果类型变量有限定，那么原始类型就用第一个边界的类型变量来替换。</p>
<p>比如Test_Generic这样声明</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test_Generic1</span>&lt;<span class="title">T</span> <span class="keyword">extends</span> <span class="title">List</span> &amp; <span class="title">Collection</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>我们还是看字节码（后面如无必须，只截取部分字节码）</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// class version 52.0 (52)</span></span><br><span class="line"><span class="comment">// access flags 0x20</span></span><br><span class="line"><span class="comment">// signature &lt;T::Ljava/util/List;:Ljava/util/Collection;&gt;Ljava/lang/Object;</span></span><br><span class="line"><span class="comment">// declaration: keyAndDifficultPoints/principle/Test_Generic1&lt;T extends java.util.List, java.util.Collection&gt;</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">keyAndDifficultPoints</span>/<span class="title">principle</span>/<span class="title">Test_Generic1</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// compiled from: Test_principle03.java</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x2</span></span><br><span class="line">  <span class="comment">// signature TT;</span></span><br><span class="line">  <span class="comment">// declaration: T</span></span><br><span class="line">  <span class="keyword">private</span> Ljava/util/List; value</span><br></pre></td></tr></table></figure>

<p>会发现T变成了List </p>
<p>如果顺序变一下</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test_Generic1</span>&lt;<span class="title">T</span> <span class="keyword">extends</span> <span class="title">Collection</span> &amp; <span class="title">List</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>字节码就变了</p>
<p>T变成了Collection</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// class version 52.0 (52)</span></span><br><span class="line"><span class="comment">// access flags 0x20</span></span><br><span class="line"><span class="comment">// signature &lt;T::Ljava/util/Collection;:Ljava/util/List;&gt;Ljava/lang/Object;</span></span><br><span class="line"><span class="comment">// declaration: keyAndDifficultPoints/principle/Test_Generic1&lt;T extends java.util.Collection, java.util.List&gt;</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">keyAndDifficultPoints</span>/<span class="title">principle</span>/<span class="title">Test_Generic1</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// compiled from: Test_principle03.java</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x2</span></span><br><span class="line">  <span class="comment">// signature TT;</span></span><br><span class="line">  <span class="comment">// declaration: T</span></span><br><span class="line">  <span class="keyword">private</span> Ljava/util/Collection; value</span><br></pre></td></tr></table></figure>

<p>也就是说在进行字节码编译的时候是使用离T最近的一个类型。</p>
<h3 id="解答一个疑惑"><a href="#解答一个疑惑" class="headerlink" title="解答一个疑惑"></a>解答一个疑惑</h3><p>在上文说到&amp;的多重限定时</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> keyAndDifficultPoints.principle;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: youthlql-吕</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/10/16 23:30</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 功能描述:</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_principle04</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">/*---------------------测试多重限定符---------------------*/</span></span><br><span class="line">        List list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        Queue queue = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        LinkedList&lt;Object&gt; linkedList = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">		 <span class="comment">//多重限定时，在编译的时候取最小范围或共同子类</span></span><br><span class="line">        test2(list);</span><br><span class="line"><span class="comment">//        test3(list); 编译报错</span></span><br><span class="line">        test4(list);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//编译报错</span></span><br><span class="line"><span class="comment">//        test2(deque);</span></span><br><span class="line"><span class="comment">//        test3(deque);</span></span><br><span class="line"><span class="comment">//        test4(queue);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//编译通过</span></span><br><span class="line">        test2(linkedList);</span><br><span class="line">        test3(linkedList);</span><br><span class="line">        test4(linkedList);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//可以进行多重限定</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T extends List &amp; Collection&gt; <span class="function"><span class="keyword">void</span> <span class="title">test2</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//可以进行多重限定</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T extends Queue &amp; List&gt; <span class="function"><span class="keyword">void</span> <span class="title">test3</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//可以进行多重限定</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T extends Collection &amp; List&gt; <span class="function"><span class="keyword">void</span> <span class="title">test4</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//编译报错，无法进行多重限定</span></span><br><span class="line"><span class="comment">//    public static &lt;? extends List &amp; Collection&gt; void test4(List&lt;T&gt; dest, List&lt;T&gt; src)&#123;</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>首先来看一下字节码</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// class version 52.0 (52)</span></span><br><span class="line"><span class="comment">// access flags 0x21</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">keyAndDifficultPoints</span>/<span class="title">principle</span>/<span class="title">Test_principle04</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// compiled from: Test_principle04.java</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x1</span></span><br><span class="line">  <span class="keyword">public</span> &lt;init&gt;()V</span><br><span class="line">   L0</span><br><span class="line">    LINENUMBER <span class="number">11</span> L0</span><br><span class="line">    ALOAD <span class="number">0</span></span><br><span class="line">    INVOKESPECIAL java/lang/Object.&lt;init&gt; ()V</span><br><span class="line">    RETURN</span><br><span class="line">   L1</span><br><span class="line">    LOCALVARIABLE <span class="keyword">this</span> LkeyAndDifficultPoints/principle/Test_principle04; L0 L1 <span class="number">0</span></span><br><span class="line">    MAXSTACK = <span class="number">1</span></span><br><span class="line">    MAXLOCALS = <span class="number">1</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x9</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="title">main</span><span class="params">([Ljava/lang/String;)</span>V</span></span><br><span class="line"><span class="function">   L0</span></span><br><span class="line"><span class="function">    LINENUMBER 17 L0</span></span><br><span class="line"><span class="function">    NEW java/util/ArrayList</span></span><br><span class="line"><span class="function">    DUP</span></span><br><span class="line"><span class="function">    INVOKESPECIAL java/util/ArrayList.&lt;init&gt; <span class="params">()</span>V</span></span><br><span class="line"><span class="function">    ASTORE 1</span></span><br><span class="line"><span class="function">   L1</span></span><br><span class="line"><span class="function">    LINENUMBER 18 L1</span></span><br><span class="line"><span class="function">    NEW java/util/ArrayDeque</span></span><br><span class="line"><span class="function">    DUP</span></span><br><span class="line"><span class="function">    INVOKESPECIAL java/util/ArrayDeque.&lt;init&gt; <span class="params">()</span>V</span></span><br><span class="line"><span class="function">    ASTORE 2</span></span><br><span class="line"><span class="function">   L2</span></span><br><span class="line"><span class="function">    LINENUMBER 19 L2</span></span><br><span class="line"><span class="function">    NEW java/util/LinkedList</span></span><br><span class="line"><span class="function">    DUP</span></span><br><span class="line"><span class="function">    INVOKESPECIAL java/util/LinkedList.&lt;init&gt; <span class="params">()</span>V</span></span><br><span class="line"><span class="function">    ASTORE 3</span></span><br><span class="line"><span class="function">   L3</span></span><br><span class="line"><span class="function">    LINENUMBER 22 L3</span></span><br><span class="line"><span class="function">    ALOAD 1</span></span><br><span class="line"><span class="function">    INVOKESTATIC keyAndDifficultPoints/principle/Test_principle04.<span class="title">test2</span> <span class="params">(Ljava/util/List;)</span>V</span></span><br><span class="line"><span class="function">   L4</span></span><br><span class="line"><span class="function">    LINENUMBER 24 L4</span></span><br><span class="line"><span class="function">    ALOAD 1</span></span><br><span class="line"><span class="function">    INVOKESTATIC keyAndDifficultPoints/principle/Test_principle04.<span class="title">test4</span> <span class="params">(Ljava/util/Collection;)</span>V</span></span><br><span class="line"><span class="function">   L5</span></span><br><span class="line"><span class="function">    LINENUMBER 33 L5</span></span><br><span class="line"><span class="function">    ALOAD 3</span></span><br><span class="line"><span class="function">    INVOKESTATIC keyAndDifficultPoints/principle/Test_principle04.<span class="title">test2</span> <span class="params">(Ljava/util/List;)</span>V</span></span><br><span class="line"><span class="function">   L6</span></span><br><span class="line"><span class="function">    LINENUMBER 34 L6</span></span><br><span class="line"><span class="function">    ALOAD 3</span></span><br><span class="line"><span class="function">    INVOKESTATIC keyAndDifficultPoints/principle/Test_principle04.<span class="title">test3</span> <span class="params">(Ljava/util/Queue;)</span>V</span></span><br><span class="line"><span class="function">   L7</span></span><br><span class="line"><span class="function">    LINENUMBER 35 L7</span></span><br><span class="line"><span class="function">    ALOAD 3</span></span><br><span class="line"><span class="function">    INVOKESTATIC keyAndDifficultPoints/principle/Test_principle04.<span class="title">test4</span> <span class="params">(Ljava/util/Collection;)</span>V</span></span><br><span class="line"><span class="function">   L8</span></span><br><span class="line"><span class="function">    LINENUMBER 38 L8</span></span><br><span class="line"><span class="function">    RETURN</span></span><br><span class="line"><span class="function">   L9</span></span><br><span class="line"><span class="function">    LOCALVARIABLE args [Ljava/lang/String</span>; L0 L9 <span class="number">0</span></span><br><span class="line">    LOCALVARIABLE list Ljava/util/List; L1 L9 <span class="number">1</span></span><br><span class="line">    LOCALVARIABLE queue Ljava/util/Queue; L2 L9 <span class="number">2</span></span><br><span class="line">    LOCALVARIABLE linkedList Ljava/util/LinkedList; L3 L9 <span class="number">3</span></span><br><span class="line">    <span class="comment">// signature Ljava/util/LinkedList&lt;Ljava/lang/Object;&gt;;</span></span><br><span class="line">    <span class="comment">// declaration: java.util.LinkedList&lt;java.lang.Object&gt;</span></span><br><span class="line">    MAXSTACK = <span class="number">2</span></span><br><span class="line">    MAXLOCALS = <span class="number">4</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x9</span></span><br><span class="line">  <span class="comment">// signature &lt;T::Ljava/util/List;:Ljava/util/Collection;&gt;(TT;)V</span></span><br><span class="line">  <span class="comment">// declaration: void test2&lt;T extends java.util.List, java.util.Collection&gt;(T)</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="title">test2</span><span class="params">(Ljava/util/List;)</span>V</span></span><br><span class="line"><span class="function">   L0</span></span><br><span class="line"><span class="function">    LINENUMBER 44 L0</span></span><br><span class="line"><span class="function">    RETURN</span></span><br><span class="line"><span class="function">   L1</span></span><br><span class="line"><span class="function">    LOCALVARIABLE t Ljava/util/List</span>; L0 L1 <span class="number">0</span></span><br><span class="line">    <span class="comment">// signature TT;</span></span><br><span class="line">    <span class="comment">// declaration: T</span></span><br><span class="line">    MAXSTACK = <span class="number">0</span></span><br><span class="line">    MAXLOCALS = <span class="number">1</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x9</span></span><br><span class="line">  <span class="comment">// signature &lt;T::Ljava/util/Queue;:Ljava/util/List;&gt;(TT;)V</span></span><br><span class="line">  <span class="comment">// declaration: void test3&lt;T extends java.util.Queue, java.util.List&gt;(T)</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="title">test3</span><span class="params">(Ljava/util/Queue;)</span>V</span></span><br><span class="line"><span class="function">   L0</span></span><br><span class="line"><span class="function">    LINENUMBER 49 L0</span></span><br><span class="line"><span class="function">    RETURN</span></span><br><span class="line"><span class="function">   L1</span></span><br><span class="line"><span class="function">    LOCALVARIABLE t Ljava/util/Queue</span>; L0 L1 <span class="number">0</span></span><br><span class="line">    <span class="comment">// signature TT;</span></span><br><span class="line">    <span class="comment">// declaration: T</span></span><br><span class="line">    MAXSTACK = <span class="number">0</span></span><br><span class="line">    MAXLOCALS = <span class="number">1</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x9</span></span><br><span class="line">  <span class="comment">// signature &lt;T::Ljava/util/Collection;:Ljava/util/List;&gt;(TT;)V</span></span><br><span class="line">  <span class="comment">// declaration: void test4&lt;T extends java.util.Collection, java.util.List&gt;(T)</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="title">test4</span><span class="params">(Ljava/util/Collection;)</span>V</span></span><br><span class="line"><span class="function">   L0</span></span><br><span class="line"><span class="function">    LINENUMBER 54 L0</span></span><br><span class="line"><span class="function">    RETURN</span></span><br><span class="line"><span class="function">   L1</span></span><br><span class="line"><span class="function">    LOCALVARIABLE t Ljava/util/Collection</span>; L0 L1 <span class="number">0</span></span><br><span class="line">    <span class="comment">// signature TT;</span></span><br><span class="line">    <span class="comment">// declaration: T</span></span><br><span class="line">    MAXSTACK = <span class="number">0</span></span><br><span class="line">    MAXLOCALS = <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p><code>test4()</code>方法里离T最近的是<code>Collection</code>，那么T在编译后就被<code>Collection</code>代替了。那按理来说</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">test4(queue);</span><br></pre></td></tr></table></figure>

<p>1、这里我们传一个Collection的实现类Queue，也应该是可以的啊，但是为什么报错了呢？注意一点报错报的是编译错误，泛型提供编译前检测机制，也就是说在没运行前，泛型规定了<code>多重限定时，在编译的时候取最小范围或共同子类</code>。</p>
<p>2、那实际上到底可以不可以传Queue呢？根据之前的讲解，我相信大家已经有了结论。实际上是可以的，只不过要跳过编译检测机制，通过反射来放Queue。</p>
<h3 id="泛型方法调用"><a href="#泛型方法调用" class="headerlink" title="泛型方法调用"></a>泛型方法调用</h3><p>​    在调用泛型方法的时候，可以指定泛型，也可以不指定泛型。在不指定泛型的情况下，泛型变量的类型为 该方法中的几种类型的同一个父类的最小级，直到Object。在指定泛型的时候，该方法中的几种类型必须是该泛型实例类型或者其子类。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//不指定泛型的时候</span></span><br><span class="line">        <span class="keyword">int</span> a1 = add(<span class="number">1</span>, <span class="number">2</span>); <span class="comment">//这两个参数都是Integer，所以T为Integer类型</span></span><br><span class="line">        Number b1 = add(<span class="number">1</span>, <span class="number">1.2</span>);<span class="comment">//这两个参数一个是Integer，以风格是Float，所以取同一父类的最小级，为Number</span></span><br><span class="line">        Object c1 = add(<span class="number">1</span>, <span class="string">&quot;my&quot;</span>);<span class="comment">//这两个参数一个是Integer，以风格是Float，所以取同一父类的最小级，为Object</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//指定泛型的时候</span></span><br><span class="line">        <span class="keyword">int</span> a = Test.&lt;Integer&gt;add(<span class="number">1</span>, <span class="number">2</span>);<span class="comment">//指定了Integer，所以只能为Integer类型或者其子类</span></span><br><span class="line"><span class="comment">//        int b = Test.&lt;Integer&gt;add(1, 2.2);//编译错误，指定了Integer，不能为Float</span></span><br><span class="line">        Number c = Test.&lt;Number&gt;add(<span class="number">1</span>, <span class="number">2.2</span>); <span class="comment">//指定为Number，所以可以为Integer和Float</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//这是一个简单的泛型方法</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">add</span><span class="params">(T x, T y)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> x;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="类型擦除引起的问题及解决方法"><a href="#类型擦除引起的问题及解决方法" class="headerlink" title="类型擦除引起的问题及解决方法"></a>类型擦除引起的问题及解决方法</h2><h3 id="类型检测针对谁？"><a href="#类型检测针对谁？" class="headerlink" title="类型检测针对谁？"></a>类型检测针对谁？</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span>  <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	ArrayList&lt;String&gt; arrayList=<span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">	arrayList.add(<span class="string">&quot;123&quot;</span>);</span><br><span class="line">	arrayList.add(<span class="number">123</span>);<span class="comment">//编译错误</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>类型擦除后，原始类型为Object，是应该运行任意引用类型的添加的。可实际上却不是这样，这恰恰说明了关于泛型变量的使用，是会在编译之前检查的。</p>
<p>那么，这么类型检查是针对谁的呢？我们来看例子：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ArrayList&lt;String&gt; arrayList = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">        arrayList.add(<span class="number">1</span>); <span class="comment">//编译报错</span></span><br><span class="line"></span><br><span class="line">        ArrayList&lt;String&gt; arrayList1 = <span class="keyword">new</span> ArrayList(); <span class="comment">//第一种 情况</span></span><br><span class="line">        arrayList1.add(<span class="number">1</span>); <span class="comment">//编译报错</span></span><br><span class="line"></span><br><span class="line">        ArrayList arrayList2 = <span class="keyword">new</span> ArrayList&lt;String&gt;();<span class="comment">//第二种 情况</span></span><br><span class="line">        arrayList2.add(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>通过上面的例子，我们可以明白，类型检查就是针对引用的，谁是一个引用，用这个引用调用泛型方法，就会对这个引用调用的方法进行类型检测，而无关它真正引用的对象。</p>
<h3 id="自动类型转换"><a href="#自动类型转换" class="headerlink" title="自动类型转换"></a>自动类型转换</h3><p>因为类型擦除的问题，所以所有的泛型类型变量最后都会被替换为原始类型。这样就引起了一个问题，既然都被替换为原始类型，那么为什么我们在获取的时候，不需要进行强制类型转换呢？</p>
<p>我么来看一下List的get()方法：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">get</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        rangeCheck(index);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> elementData(index);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line"><span class="function">E <span class="title">elementData</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (E) elementData[index];</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>可以看到基本各个类都已经自动帮你转了。</p>
<h3 id="类型擦除与多态的冲突和解决方法"><a href="#类型擦除与多态的冲突和解决方法" class="headerlink" title="类型擦除与多态的冲突和解决方法"></a>类型擦除与多态的冲突和解决方法</h3><p>这个其实是类型擦除引起的最大的问题了。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test_principle05</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Generic</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">//key这个成员变量的类型为T,T的类型由外部指定</span></span><br><span class="line">    <span class="keyword">private</span> T <span class="keyword">var</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getVar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setVar</span><span class="params">(T <span class="keyword">var</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.<span class="keyword">var</span> = <span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyGeneric</span> <span class="keyword">extends</span> <span class="title">Generic</span>&lt;<span class="title">Integer</span>&gt;</span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getVar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">super</span>.getVar();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setVar</span><span class="params">(Integer <span class="keyword">var</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.setVar(<span class="keyword">var</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实际上，从他们的@Override标签中也可以看到，在子类中重写这两个方法一点问题也没有，实际上是这样的吗？</p>
<p><strong>分析：</strong></p>
<p>泛型擦除后，父类是下面这样子</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Generic</span> </span>&#123;</span><br><span class="line">    <span class="comment">//key这个成员变量的类型为T,T的类型由外部指定</span></span><br><span class="line">    <span class="keyword">private</span> Object <span class="keyword">var</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">getVar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setVar</span><span class="params">(Object <span class="keyword">var</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.<span class="keyword">var</span> = <span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>子类还是这样</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyGeneric</span> <span class="keyword">extends</span> <span class="title">Generic</span>&lt;<span class="title">Integer</span>&gt;</span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getVar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">super</span>.getVar();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setVar</span><span class="params">(Integer <span class="keyword">var</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.setVar(<span class="keyword">var</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>先来分析setValue方法，父类的类型是Object，而子类的类型是Date，参数类型不一样，这如果实在普通的继承关系中，根本就不会是重写，而是重载。</p>
<blockquote>
<p><strong>重载（Overload）:首先是位于一个类之中或者其子类中，具有相同的方法名，但是方法的参数不同，返回值类型可以相同也可以不同。</strong></p>
<p>（1）：方法名必须相同。</p>
<p>（2）：方法的参数列表一定不一样。</p>
<p>（3）：访问修饰符和返回值类型可以相同也可以不同。</p>
<p><strong>重写（override）：一般都是表示子类和父类之间的关系，其主要的特征是：方法名相同，参数相同，但是具体的实现不同。</strong></p>
<p><strong>重写的特征：</strong></p>
<p>（1）：方法名必须相同，返回值类型必须相同</p>
<p>（2）：参数列表必须相同</p>
<p>（3）：访问权限不能比父类中被重写的方法的访问权限更低。例如：如果父类的一个方法被声明为public，那么在子类中重写该方法就不能声明为protected。</p>
<p>（4）：子类和父类在同一个包中，那么子类可以重写父类所有方法，除了声明为private和final的方法。</p>
<p>（5）：构造方法不能被重写</p>
</blockquote>
<p>我们来测试下到底是重载还是重写</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">       MyGeneric myGeneric = <span class="keyword">new</span> MyGeneric();</span><br><span class="line">       myGeneric.setVar(<span class="keyword">new</span> Integer(<span class="number">1</span>));</span><br><span class="line">       myGeneric.setVar(<span class="keyword">new</span> Object());<span class="comment">//编译错误</span></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>如果是重载的话，第四行代码是不会报错的，因为调的是不同的重载方法。但是发现编译报错了，也就是说没有参数是Object的这样的重载函数。所以说是重写了，导致MyGeneric对象只能调用自己重写的方法。</p>
<p>为什么会这样呢？</p>
<p>原因是这样的，我们传入父类的泛型类型是Integer，Generic<Integer>，我们的本意是将泛型类变为如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Generic</span> </span>&#123;</span><br><span class="line">    <span class="comment">//key这个成员变量的类型为T,T的类型由外部指定</span></span><br><span class="line">    <span class="keyword">private</span> Integer <span class="keyword">var</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getVar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setVar</span><span class="params">(Integer <span class="keyword">var</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.<span class="keyword">var</span> = <span class="keyword">var</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后再子类中重写参数类型为Date的那两个方法，实现继承中的多态。</p>
<p>​    可是由于种种原因，虚拟机并不能将泛型类型变为Integer，只能将类型擦除掉，变为原始类型Object。这样，我们的本意是进行重写，实现多态。可是类型擦除后，只能变为了重载。这样，类型擦除就和多态有了冲突。JVM知道你的本意吗？知道，可是它能直接实现吗，不能。如果真的不能的话，那我们怎么去重写我们想要的Integer类型参数的方法啊。</p>
<p>JVM采用了一个特殊的方法，来完成这项功能，那就是<strong>桥方法</strong>。</p>
<p>我们对下面这个类进行编译，看其字节码</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyGeneric</span> <span class="keyword">extends</span> <span class="title">Generic</span>&lt;<span class="title">Integer</span>&gt;</span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getVar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">super</span>.getVar();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setVar</span><span class="params">(Integer <span class="keyword">var</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.setVar(<span class="keyword">var</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>字节码：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// class version 52.0 (52)</span></span><br><span class="line"><span class="comment">// access flags 0x21</span></span><br><span class="line"><span class="comment">// signature LkeyAndDifficultPoints/principle/Generic&lt;Ljava/lang/Integer;&gt;;</span></span><br><span class="line"><span class="comment">// declaration: keyAndDifficultPoints/principle/MyGeneric extends keyAndDifficultPoints.principle.Generic&lt;java.lang.Integer&gt;</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">keyAndDifficultPoints</span>/<span class="title">principle</span>/<span class="title">MyGeneric</span> <span class="keyword">extends</span> <span class="title">keyAndDifficultPoints</span>/<span class="title">principle</span>/<span class="title">Generic</span>  </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// compiled from: MyGeneric.java</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x1</span></span><br><span class="line">  <span class="keyword">public</span> &lt;init&gt;()V</span><br><span class="line">   L0</span><br><span class="line">    LINENUMBER <span class="number">9</span> L0</span><br><span class="line">    ALOAD <span class="number">0</span></span><br><span class="line">    INVOKESPECIAL keyAndDifficultPoints/principle/Generic.&lt;init&gt; ()V</span><br><span class="line">    RETURN</span><br><span class="line">   L1</span><br><span class="line">    LOCALVARIABLE <span class="keyword">this</span> LkeyAndDifficultPoints/principle/MyGeneric; L0 L1 <span class="number">0</span></span><br><span class="line">    MAXSTACK = <span class="number">1</span></span><br><span class="line">    MAXLOCALS = <span class="number">1</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x9</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="title">main</span><span class="params">([Ljava/lang/String;)</span>V</span></span><br><span class="line"><span class="function">   L0</span></span><br><span class="line"><span class="function">    LINENUMBER 12 L0</span></span><br><span class="line"><span class="function">    RETURN</span></span><br><span class="line"><span class="function">   L1</span></span><br><span class="line"><span class="function">    LOCALVARIABLE args [Ljava/lang/String</span>; L0 L1 <span class="number">0</span></span><br><span class="line">    MAXSTACK = <span class="number">0</span></span><br><span class="line">    MAXLOCALS = <span class="number">1</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x1</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">getVar</span><span class="params">()</span>Ljava/lang/Integer</span>;  <span class="comment">//这是我们重写的getVar()方法</span></span><br><span class="line">   L0</span><br><span class="line">    LINENUMBER <span class="number">16</span> L0</span><br><span class="line">    ALOAD <span class="number">0</span></span><br><span class="line">    INVOKESPECIAL keyAndDifficultPoints/principle/Generic.getVar ()Ljava/lang/Object;</span><br><span class="line">    CHECKCAST java/lang/Integer</span><br><span class="line">    ARETURN</span><br><span class="line">   L1</span><br><span class="line">    LOCALVARIABLE <span class="keyword">this</span> LkeyAndDifficultPoints/principle/MyGeneric; L0 L1 <span class="number">0</span></span><br><span class="line">    MAXSTACK = <span class="number">1</span></span><br><span class="line">    MAXLOCALS = <span class="number">1</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x1</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">setVar</span><span class="params">(Ljava/lang/Integer;)</span>V  <span class="comment">////这是我们重写的setVar()方法</span></span></span><br><span class="line"><span class="function">   L0</span></span><br><span class="line"><span class="function">    LINENUMBER 20 L0</span></span><br><span class="line"><span class="function">    ALOAD 0</span></span><br><span class="line"><span class="function">    ALOAD 1</span></span><br><span class="line"><span class="function">    INVOKESPECIAL keyAndDifficultPoints/principle/Generic.<span class="title">setVar</span> <span class="params">(Ljava/lang/Object;)</span>V</span></span><br><span class="line"><span class="function">   L1</span></span><br><span class="line"><span class="function">    LINENUMBER 21 L1</span></span><br><span class="line"><span class="function">    RETURN</span></span><br><span class="line"><span class="function">   L2</span></span><br><span class="line"><span class="function">    LOCALVARIABLE <span class="keyword">this</span> LkeyAndDifficultPoints/principle/MyGeneric</span>; L0 L2 <span class="number">0</span></span><br><span class="line">    LOCALVARIABLE <span class="keyword">var</span> Ljava/lang/Integer; L0 L2 <span class="number">1</span></span><br><span class="line">    MAXSTACK = <span class="number">2</span></span><br><span class="line">    MAXLOCALS = <span class="number">2</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x1041</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> synthetic bridge <span class="title">setVar</span><span class="params">(Ljava/lang/Object;)</span>V  <span class="comment">//编译时由编译器生成的桥方法</span></span></span><br><span class="line"><span class="function">   L0</span></span><br><span class="line"><span class="function">    LINENUMBER 9 L0</span></span><br><span class="line"><span class="function">    ALOAD 0</span></span><br><span class="line"><span class="function">    ALOAD 1</span></span><br><span class="line"><span class="function">    CHECKCAST java/lang/Integer</span></span><br><span class="line"><span class="function">    INVOKEVIRTUAL keyAndDifficultPoints/principle/MyGeneric.<span class="title">setVar</span> <span class="params">(Ljava/lang/Integer;)</span>V</span></span><br><span class="line"><span class="function">    RETURN</span></span><br><span class="line"><span class="function">   L1</span></span><br><span class="line"><span class="function">    LOCALVARIABLE <span class="keyword">this</span> LkeyAndDifficultPoints/principle/MyGeneric</span>; L0 L1 <span class="number">0</span></span><br><span class="line">    MAXSTACK = <span class="number">2</span></span><br><span class="line">    MAXLOCALS = <span class="number">2</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// access flags 0x1041</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> synthetic bridge <span class="title">getVar</span><span class="params">()</span>Ljava/lang/Object</span>;  <span class="comment">//编译时由编译器生成的桥方法</span></span><br><span class="line">   L0</span><br><span class="line">    LINENUMBER <span class="number">9</span> L0</span><br><span class="line">    ALOAD <span class="number">0</span></span><br><span class="line">    INVOKEVIRTUAL keyAndDifficultPoints/principle/MyGeneric.getVar ()Ljava/lang/Integer;</span><br><span class="line">    ARETURN</span><br><span class="line">   L1</span><br><span class="line">    LOCALVARIABLE <span class="keyword">this</span> LkeyAndDifficultPoints/principle/MyGeneric; L0 L1 <span class="number">0</span></span><br><span class="line">    MAXSTACK = <span class="number">1</span></span><br><span class="line">    MAXLOCALS = <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>​    从编译的结果来看，我们本意重写setValue和getValue方法的子类，竟然有4个方法。最后的两个方法，就是编译器自己生成的桥方法。可以看到桥方法的参数类型都是Object，也就是说，子类中真正覆盖父类两个方法的就是这两个我们看不到的桥方法。而打在我们自己定义的setvalue和getValue方法上面的@Oveerride只不过是假象。而桥方法的内部实现，就只是去调用我们自己重写的那两个方法。</p>
<p>所以，虚拟机巧妙的使用了巧方法，来解决了类型擦除和多态的冲突。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/adb2faf0.html">https://imlql.cn/post/adb2faf0.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a><a class="post-meta__tags" href="/tags/%E5%9F%BA%E7%A1%80/">基础</a><a class="post-meta__tags" href="/tags/%E6%B3%9B%E5%9E%8B/">泛型</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/92c4503d.html"><img class="prev-cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/Java_concurrency.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Java并发体系-第四阶段-AQS源码解读-[1]</div></div></a></div><div class="next-post pull-right"><a href="/post/de3879ae.html"><img class="next-cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/java.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">详解JDK8新特性</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AE%80%E4%BB%8B"><span class="toc-text">简介</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E7%9A%84%E4%BC%98%E7%82%B9"><span class="toc-text">泛型的优点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E6%8F%90%E9%AB%98%E4%BA%86%E5%AE%89%E5%85%A8%E6%80%A7%EF%BC%9F"><span class="toc-text">为什么提高了安全性？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E4%B8%BA%E4%BB%80%E4%B9%88%E5%BE%88%E9%87%8D%E8%A6%81"><span class="toc-text">泛型为什么很重要</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E7%B1%BB"><span class="toc-text">泛型类</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E6%8E%A5%E5%8F%A3"><span class="toc-text">泛型接口</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E6%96%B9%E6%B3%95"><span class="toc-text">泛型方法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95%EF%BC%88%E9%9D%9E%E6%B3%9B%E5%9E%8B%E7%B1%BB%E4%B8%AD%E7%9A%84%E6%B3%9B%E5%9E%8B%E6%96%B9%E6%B3%95%EF%BC%89"><span class="toc-text">基本用法（非泛型类中的泛型方法）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E7%B1%BB%E4%B8%AD%E7%9A%84%E6%B3%9B%E5%9E%8B%E6%96%B9%E6%B3%95"><span class="toc-text">泛型类中的泛型方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E6%96%B9%E6%B3%95%E4%B8%8E%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0"><span class="toc-text">泛型方法与可变参数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95%E4%B8%8E%E6%B3%9B%E5%9E%8B"><span class="toc-text">静态方法与泛型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%86%E6%9E%9D%E6%9C%AB%E8%8A%82"><span class="toc-text">细枝末节</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E6%95%B0%E7%BB%84"><span class="toc-text">泛型数组</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E5%9C%A8%E7%BB%A7%E6%89%BF%E6%96%B9%E9%9D%A2%E7%9A%84%E7%BB%86%E8%8A%82"><span class="toc-text">泛型在继承方面的细节</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E9%80%9A%E9%85%8D%E7%AC%A6"><span class="toc-text">泛型通配符</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E7%9A%84%E9%80%9A%E9%85%8D%E7%AC%A6"><span class="toc-text">常用的通配符</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E2%80%98-%E2%80%98%E6%97%A0%E7%95%8C%E9%80%9A%E9%85%8D%E7%AC%A6"><span class="toc-text">‘ ? ‘无界通配符</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95"><span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E2%80%98-%E2%80%98%E9%80%9A%E9%85%8D%E7%AC%A6%E7%9A%84%E7%BB%A7%E6%89%BF"><span class="toc-text">‘ ? ‘通配符的继承</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#extends%E5%92%8Csuper%E4%B8%8A%E4%B8%8B%E7%95%8C"><span class="toc-text">extends和super上下界</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%8A%E7%95%8C%E9%80%9A%E9%85%8D%E7%AC%A6-lt-extends-E-gt"><span class="toc-text">上界通配符 &lt; ? extends E&gt;</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%8B%E7%95%8C%E9%80%9A%E9%85%8D%E7%AC%A6-lt-super-E-gt"><span class="toc-text">下界通配符 &lt; ? super E&gt;</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%BE%8B"><span class="toc-text">举例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8C%BA%E5%88%AB1%EF%BC%9A%E9%80%9A%E8%BF%87T%E6%9D%A5%E7%A1%AE%E4%BF%9D%E6%B3%9B%E5%9E%8B%E5%8F%82%E6%95%B0%E7%9A%84%E4%B8%80%E8%87%B4%E6%80%A7"><span class="toc-text">区别1：通过T来确保泛型参数的一致性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8C%BA%E5%88%AB2%EF%BC%9AT%E5%8F%AF%E4%BB%A5%E9%80%9A%E8%BF%87-amp-%E8%BF%9B%E8%A1%8C%E5%A4%9A%E9%87%8D%E9%99%90%E5%AE%9A"><span class="toc-text">区别2：T可以通过&amp;进行多重限定</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8C%BA%E5%88%AB3%EF%BC%9A%EF%BC%9F%E9%80%9A%E9%85%8D%E7%AC%A6%E5%8F%AF%E4%BB%A5%E4%BD%BF%E7%94%A8%E8%B6%85%E7%B1%BB%E9%99%90%E5%AE%9A%E8%80%8CT%E4%B8%8D%E8%A1%8C"><span class="toc-text">区别3：？通配符可以使用超类限定而T不行</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%B3%E4%BA%8E%E5%8F%8D%E5%B0%84%E5%92%8C%E6%B3%9B%E5%9E%8B%E7%9A%84%E4%B8%80%E7%82%B9%E4%B8%9C%E8%A5%BF"><span class="toc-text">关于反射和泛型的一点东西</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E5%8E%9F%E7%90%86%EF%BC%88%E6%B3%9B%E5%9E%8B%E6%93%A6%E9%99%A4%EF%BC%89"><span class="toc-text">泛型原理（泛型擦除）</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB%E5%9E%8B%E6%93%A6%E9%99%A4%E7%AE%80%E4%BB%8B"><span class="toc-text">类型擦除简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB%E5%9E%8B%E6%93%A6%E9%99%A4%E5%90%8E%E4%BF%9D%E7%95%99%E7%9A%84%E5%8E%9F%E5%A7%8B%E7%B1%BB%E5%9E%8B"><span class="toc-text">类型擦除后保留的原始类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%A3%E7%AD%94%E4%B8%80%E4%B8%AA%E7%96%91%E6%83%91"><span class="toc-text">解答一个疑惑</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E6%96%B9%E6%B3%95%E8%B0%83%E7%94%A8"><span class="toc-text">泛型方法调用</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB%E5%9E%8B%E6%93%A6%E9%99%A4%E5%BC%95%E8%B5%B7%E7%9A%84%E9%97%AE%E9%A2%98%E5%8F%8A%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95"><span class="toc-text">类型擦除引起的问题及解决方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B1%BB%E5%9E%8B%E6%A3%80%E6%B5%8B%E9%92%88%E5%AF%B9%E8%B0%81%EF%BC%9F"><span class="toc-text">类型检测针对谁？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%8A%A8%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="toc-text">自动类型转换</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B1%BB%E5%9E%8B%E6%93%A6%E9%99%A4%E4%B8%8E%E5%A4%9A%E6%80%81%E7%9A%84%E5%86%B2%E7%AA%81%E5%92%8C%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95"><span class="toc-text">类型擦除与多态的冲突和解决方法</span></a></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>